#pragma once

#include <iostream>
#include <string>
#include <sys/epoll.h>
#include "log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;
const int revs_num = 64;

enum
{
    EPOLL_CREATE_ERROR = 1,
    EPOLL_CTL_ERROR
};

class EpollServer
{
public:
    EpollServer(uint16_t port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _is_running(false), _epfd(gdefaultfd)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpsocketMethood(_port);
        // 1. 创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(ERROR, "eopll_create error!\n");
            exit(EPOLL_CREATE_ERROR);
        }
        LOG(DEBUG, "eopll_create success! _epfd: %d\n", _epfd);

        // 2. 至少要将listensockfd添加到epoll模型中
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_socket->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->Fd(), &ev);
        if (n < 0)
        {
            LOG(ERROR, "eopll_ctl error!\n");
            exit(EPOLL_CTL_ERROR);
        }
    }

    void Loop()
    {
        _is_running = true;
        int timeout = 1000;
        while (_is_running)
        {
            int n = epoll_wait(_epfd, _revs, revs_num, timeout);
            switch (n)
            {
            case 0:
                std::cout << "timeout..." << std::endl;
                break;
            case -1:
                perror("epoll_wait");
                break;
            default:
                std::cout << "有事件就绪了!" << std::endl;
                Dispatcher(n); // 将已经就绪的事件派发给指定的模块
                break;
            }
        }
        _is_running = false;
    }

    void Accept()
    {
        InetAddr client;
        int newfd = _listen_socket->accepter(&client);
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得了一个新的连接: " << newfd << "client info: " << client.AddrStr() << std::endl;
            // 需要将新的newfd添加到epoll
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = newfd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
            if (n < 0)
            {
                LOG(ERROR, "eopll_ctl error!\n");
                close(newfd);
            }
            LOG(DEBUG, "eopll_ctl success! newfd: %d\n", newfd);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;

            std::string message = "echo# ";
            message += buffer;
            send(fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(DEBUG, "客户端退出, sockfd: %d\n", fd);
            // 将文件描述符从epoll中移除，注意：必须保证fd是合法的
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0)
            {
                LOG(ERROR, "eopll_ctl error!\n");
                return;
            }
            LOG(DEBUG, "eopll_ctl success! fd: %d\n", fd);
            close(fd);
        }
        else
        {
            LOG(DEBUG, "客户端读取出错, sockfd: %d\n", fd);
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0)
            {
                LOG(ERROR, "eopll_ctl error!\n");
                return;
            }
            LOG(DEBUG, "eopll_ctl success! fd: %d\n", fd);
            close(fd);
        }
    }

    void Dispatcher(int rnum)
    {
        for (size_t i = 0; i < rnum; i++)
        {
            int events = _revs[i].events;
            int fd = _revs[i].data.fd;
            if (fd == _listen_socket->Fd())
            {
                // listen sock fd就绪
                if (events & EPOLLIN)
                {
                    Accept();
                }
            }
            else
            {
                // 普通文件描述符就绪
                if (events & EPOLLIN)
                {
                    // 读事件就绪
                    Recver(fd);
                }
            }
        }
    }

    ~EpollServer()
    {
        _listen_socket->Close();
        if (_epfd > 0)
            close(_epfd);
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;

    bool _is_running;

    int _epfd;
    struct epoll_event _revs[revs_num];
};